import { Effect, Reducer, Subscription } from 'umi';
// 部门下拉树
import { treeselect, deeps } from '@/api/system/dept.js';

export interface DeptModelType {
  namespace: 'dept';
  state: {};
  reducers: {
    savetreeData: Reducer;
  };
  effects: {
    deptGetTreeselect: Effect;
  };
  subscriptions: {
    getTreeselect: Subscription;
  };
}

const DeptModel: DeptModelType = {
  namespace: 'dept',
  state: {
    treeData: [],
  },
  reducers: {
    savetreeData(state, { payload }) {
      const tree = deeps(payload.tree);
      return {
        ...state,
        treeData: tree,
      };
    },
  },
  effects: {
    /** 查询部门下拉树结构 */
    *deptGetTreeselect({ payload }, { call, put }) {
      const res = yield call(treeselect);
      yield put({
        type: 'savetreeData',
        payload: {
          tree: res.data,
        },
      });
    },
  },
  subscriptions: {
    getTreeselect({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/system/user') {
          dispatch({
            type: 'deptGetTreeselect',
          });
        }
      });
    },
  },
};
export default DeptModel;
